global date "date_threshold"

global masterstartthresh = 2
local start=${masterstartthresh}

local samplecount=0
foreach sample in all all_va{
foreach thresh of numlist [withheld] {
  local samplecount=`samplecount'+1
  local priorsample=`samplecount'-1
  global masterthresh=`thresh'
  global agegroup "`sample'"
  global sample "`sample'"
  local agegroup "${agegroup}"
  local ltfpvar tfpvar

  quietly use "${data}/data_`agegroup'.dta", clear
  quietly bys S J: gen cellcount=_N

	keep if cellcount>=`thresh'
	cap drop lA
	quietly cap rename `ltfpvar' lA

	*Groups
	quietly egen JT		= group(J T)
	quietly egen ST		= group(S T)
	quietly egen SJT	= group(S J T)
	quietly egen tag_SJT	= tag(SJT)
	quietly egen tag_ST	= tag(ST)
	
	*Tau weights  
	quietly bys SJT	: egen emp_SJT	= total(empl*(lA!=.))
	quietly bys ST	: egen emp_ST	= total(empl*(lA!=.))
	quietly gen empshare_SJT		= emp_SJT/emp_ST
	
	*Number of Cells and Avg Plants per Cell
	quietly gen N_total 			= _N
	quietly egen N_ST 				= total(tag_ST)
	quietly egen N_SJT				= total(tag_SJT)
	quietly gen plants_percell_capT	= N_total / N_ST
	quietly gen plants_percell_tau	= N_total / N_SJT
		
		*Taus
		quietly reghdfe lA [aw=empl], absorb(temp_tau=SJT) keepsingletons
		quietly reghdfe temp_tau  if tag_SJT, absorb(JT) resid keepsingletons
		quietly predict tau if e(sample), resid	
			
		*CapT
		quietly reghdfe tau [aw=empshare_SJT], absorb(capT_temp=ST)  keepsingletons
		quietly reghdfe capT_temp if tag_ST, absorb(T) resid keepsingletons
		quietly predict capT if e(sample), resid

		*Calculate variances, save var and N, verify mean==0
		quietly tabstat capT if tag_ST, stat(N var mean) save
		matrix stats		= r(StatTotal)
		quietly gen N_capT	= stats[1,1]
		quietly gen var_capT= stats[2,1]
		
		quietly tabstat  tau [aw=empshare_SJT]  if tag_SJT, stat(N var mean) save
		matrix stats		= r(StatTotal)
		quietly gen N_tau	= stats[1,1]
		quietly gen var_tau	= stats[2,1]	
	
		rename capT capTtemp
		rename tau tautemp
		bys S T: 	egen capT	= max(capTtemp)
		bys S J T: 	egen tau	= max(tautemp)
		quietly keep if _n==1
		quietly keep var*  N_total N_ST N_SJT 
		quietly gen sample="`sample'"
		quietly gen thresh=`thresh'
		format var* %9.4g		
				
  if (`thresh'==${masterstartthresh} ){
	quietly save "${results}/temp/thresh_results${date}.dta", replace
	}
	else{
	quietly append using "${results}/temp/thresh_results${date}.dta"
	quietly save "${results}/temp/thresh_results${date}.dta", replace
	}
 
 

do "${code}/Permute_threshold.do"

do "${code}/Cov_threshold.do"

}



use "${results}/temp/thresh_results${date}.dta",clear

foreach var of varlist _all{
		cap rename `var' `var'_num
		cap gen `var'=string(`var'_num,"%9.4g")
		drop `var'_num
	}

order thresh  var* perm* *
if "`sample'"=="all"{
export delimited using "${results}/Fig4.csv", replace
}
else{
export delimited using "${results}/FigA3.csv", replace
}
}
